/**
 * UI 交互模块
 */

document.addEventListener("DOMContentLoaded", () => {
  // 初始化通用
  initCommon()
  // 初始化主题
  initTheme()

  // 初始化主题切换
  initThemeModal()

  // 初始化下拉菜单
  initDropdowns()

  // 初始化媒体卡片交互
  initMediaCardInteractions()

  // 初始化设置按钮
  initSettingsButton()
})

/**
 * 初始化通用
 */
function initCommon() {
  const sidebarElemet = document.getElementById("sidebar")

  sidebarElemet.innerHTML =`
  <div class="sidebar-header">
          <div class="logo">
            <i class="ri-film-line"></i>
            <span class="logo-text">飞牛影视</span>
          </div>
          <button class="btn-icon sidebar-close-btn" id="sidebarCloseBtn">
            <i class="ri-close-line"></i>
          </button>
        </div>
  
        <div class="sidebar-content">
          <nav class="sidebar-nav">
            <a href="index.html" class="nav-item active">
              <i class="ri-home-line"></i>
              <span>首页</span>
            </a>
            <a href="favorites.html" class="nav-item">
              <i class="ri-heart-line"></i>
              <span>收藏</span>
            </a>
          </nav>
  
          <div class="sidebar-section" data-section="media-library">
            <div class="section-header">
              <button class="section-toggle">
                <i class="ri-arrow-down-s-line"></i>
              </button>
              <h3>媒体库</h3>
            </div>
            <div class="section-content" id="mediaLibraryContent">
            </div>
          </div>
  
          <div class="sidebar-section" data-section="categories">
            <div class="section-header">
              <button class="section-toggle">
                <i class="ri-arrow-down-s-line"></i>
              </button>
              <h3>分类</h3>
            </div>
            <div class="section-content">
              <a href="category.html?type=all" class="nav-item">
                <i class="ri-stack-line"></i>
                <span>全部</span>
                <span class="badge">24</span>
              </a>
            </div>
          </div>
        </div>
  
        <div class="sidebar-footer">
          <div class="dropdown">
            <button class="btn-source" id="sourceButton">
              <i class="ri-database-2-line"></i>
              <span>切换源</span>
              <i class="ri-arrow-down-s-line"></i>
            </button>
            <div class="source-dropdown" id="sourceDropdown">
              <div id="sourceList">
                <!-- 源列表将通过JS动态生成 -->
              </div>
            </div>
            <button class="btn-collapse" id="collapseButton">
              <i class="ri-arrow-left-s-line"></i>
            </button>
          </div>        
        </div>
  `
  const headerElement = document.getElementById("header")
  headerElement.innerHTML = `
   <button class="btn-icon menu-toggle" id="menuToggle">
            <i class="ri-menu-line"></i>
          </button>
          
          <div class="header-actions">
            <div class="search-container" id="searchContainer">
              <form id="searchForm" class="search-form">
                <input type="search" id="searchInput" placeholder="搜索..." class="search-input">
                <button type="submit" class="btn-search">
                  <i class="ri-search-line"></i>
                </button>
                <button type="button" class="btn-close-search" id="closeSearch">
                  <i class="ri-close-line"></i>
                </button>
              </form>
            </div> 
            <button class="btn-icon" id="searchToggle">
              <i class="ri-search-line"></i>
            </button>
            <button class="btn-icon" id="themeToggle">
              <i class="ri-moon-line"></i>
            </button>
            <button class="btn-icon" id="settingsButton">
              <i class="ri-settings-3-line"></i>
            </button>
          </div>
  `
    // 初始化侧边栏
    initSidebar()

    // 更新分类
    getCategory()
  
    // 初始化搜索
    initSearch()
  
    // 初始化源切换
    initSourceDropdown()
}
/**
 * 初始化主题
 */
function initTheme() {
  const config = window.AppConfig.getConfig()
  const theme = config.ui.theme || "dark"

  // 设置主题类
  document.body.className = `theme-${theme}`

  // 更新主题切换按钮图标
  const themeToggleBtn = document.getElementById("themeToggle")
  if (themeToggleBtn) {
    themeToggleBtn.innerHTML = theme === "dark" ? '<i class="ri-sun-line"></i>' : '<i class="ri-moon-line"></i>'
  }

  // 监听主题切换按钮点击
  themeToggleBtn?.addEventListener("click", () => {
    const themeModal = document.getElementById("themeModal")
    if (themeModal) {
      themeModal.classList.add("open")
    }
  })
}

/**
 * 初始化侧边栏
 */
function initSidebar() {
  const config = window.AppConfig.getConfig()
  const sidebar = document.getElementById("sidebar")
  const sidebarOverlay = document.getElementById("sidebarOverlay")
  const menuToggle = document.getElementById("menuToggle")
  const sidebarCloseBtn = document.getElementById("sidebarCloseBtn")
  const collapseButton = document.getElementById("collapseButton")

  // 设置侧边栏折叠状态
  if (config.ui.sidebarCollapsed) {
    document.body.classList.add("sidebar-collapsed")
  }

  // 设置侧边栏分组折叠状态
  const mediaLibrarySection = document.querySelector('[data-section="media-library"]')
  const categoriesSection = document.querySelector('[data-section="categories"]')

  if (!config.ui.mediaLibraryOpen && mediaLibrarySection) {
    mediaLibrarySection.classList.add("section-collapsed")
  }

  if (!config.ui.categoriesOpen && categoriesSection) {
    categoriesSection.classList.add("section-collapsed")
  }

  // 监听菜单按钮点击
  menuToggle?.addEventListener("click", () => {
    document.body.classList.add("sidebar-open")
  })

  // 监听侧边栏关闭按钮点击
  sidebarCloseBtn?.addEventListener("click", () => {
    document.body.classList.remove("sidebar-open")
  })

  // 监听遮罩点击
  sidebarOverlay?.addEventListener("click", () => {
    document.body.classList.remove("sidebar-open")
  })

  // 监听折叠按钮点击
  collapseButton?.addEventListener("click", () => {
    const isCollapsed = document.body.classList.toggle("sidebar-collapsed")
    window.AppConfig.updateNestedConfig("ui.sidebarCollapsed", isCollapsed)
    sourceButton?.classList.toggle("hidden")
  })

  // 监听分组标题点击
  const sectionToggles = document.querySelectorAll(".section-toggle")
  sectionToggles.forEach((toggle) => {
    toggle.addEventListener("click", () => {
      const section = toggle.closest(".sidebar-section")
      const sectionId = section.dataset.section
      const isCollapsed = section.classList.toggle("section-collapsed")
      window.AppConfig.updateNestedConfig(`ui.${sectionId}Open`, !isCollapsed)
    })
  })

  // 更新侧边栏徽章
  updateSidebarBadges()
}

/**
 * 更新侧边栏徽章
 */
function updateSidebarBadges() {
  const getConfig = window.AppConfig.getConfig().cache.total
  if (!getConfig) return
  const typeMap = {
    movie: document.querySelector("#category_movie"),
    tv: document.querySelector("#category_tv"),
    anime: document.querySelector("#category_anime"),
    variety: document.querySelector("#category_variety"),
    other: document.querySelector("#category_other"),
    adult: document.querySelector("#category_adult"),
  }

  // 设置当前源类型的徽章
  Object.keys(typeMap).forEach((type) => {
    const badge = typeMap[type]
    if (badge) {
      badge.textContent = getConfig[type] ? getConfig[type] : "0"
    }
  })
}


/**
 * 获取分类
 */
async function getCategory() {
  const config = window.AppConfig.getConfig()
  const activeSource = window.AppConfig.getActiveSource()
  const categories = config.data.categories || []
  try {   
    if(categories.length === 0){
      const response = await window.API.getCategories(activeSource)
      // 处理响应数据
      if (response && Array.isArray(response)) {
        // 处理响应数据
        const categories = response.map(category => ({
          id: category.type_id,
          name: category.type_name,
          type_pid: category.type_pid,
          subcategories: category.sub ? category.sub.split(',') : []
        }));
        // 存储到缓存中
        window.AppConfig.updateNestedConfig('data.categories', categories)
      }
    }
    setCategory()
  }catch (error) {
    console.error('Error fetching categories:', error);
  }
}

function setCategory(){
  const categorized = loadCategorized()
  // 更新导航栏
  const mediaLibraryContent = document.getElementById("mediaLibraryContent")
  mediaLibraryContent.innerHTML = `` 
  const categoryItemIcon = {
    movie: '<i class="ri-film-line"></i>',
    tv: '<i class="ri-tv-line"></i>',
    anime: '<i class="ri-movie-line"></i>',
    variety: '<i class="ri-emotion-line"></i>',
    other: '<i class="ri-stack-line"></i>',
  }
  categorized.forEach((category) => {
    const categoryItem = document.createElement("a");
    categoryItem.className = "nav-item";
    categoryItem.id = `nav-${category.id}`;
    categoryItem.href = `category.html?type=${category.type}`;
    categoryItem.innerHTML = `
              ${categoryItemIcon[category.type]}
              <span>${category.name}</span>
              <span class="badge" id="category_${category.type}"></span>
            `;
    mediaLibraryContent.appendChild(categoryItem);
  });
  updateSidebarBadges()
}


function loadCategorized(){
  const config = window.AppConfig.getConfig()
  const categories = config.data.categories || []
  const source = window.AppConfig.getActiveSource()
  let categorized = []
  if (source.type == '18+') {
    categorized = setFreeNav(categories);
  }else{
    categorized = autoCategorize(categories, categorieConfig);
  }
  return categorized
}

/**
 * 自动将获取的类别列归类到预定义的类别列表中
 * @param {Array} fetchedCategories - 从外部获取的类别列表
 * @param {Array} predefinedCategories - 预定义的类别列表
 * @returns {Array} - 归类后的类别列表
 */
function autoCategorize(fetchedCategories, predefinedCategories) {
  const categorized = [];
  for (let i = 0; i < predefinedCategories.length; i++) {
    const predefinedCategory = predefinedCategories[i];
    const matchingSubcategories = fetchedCategories.filter(fetchedCategory => {
      return predefinedCategory.class.some(classValue => fetchedCategory.name.includes(classValue));
    });
    // 如果有匹配的子类别，将其添加到当前类别的 subcategories 数组中
    predefinedCategory.subcategories = matchingSubcategories.length > 0 ? matchingSubcategories : [];
    // 将当前类别添加到归类后的列表中
    categorized.push(predefinedCategory);
  }
  return categorized;
}
/**
 * freeNav
 * 
 */
function setFreeNav(categorie) {
  //每10个分为一组，
  const groupSize = 10;
  const groups = [];
  const categorized = [];
  for (let i = 0; i < categorie.length; i += groupSize) {
    groups.push(categorie.slice(i, i + groupSize));
  }
  //每组归类
  groups.forEach((group, i) => {
    categorized.push({ id: i + 1, name: '第' + (i + 1) + '组',type: `team_${i}`, subcategories: group });
  })
  return categorized;
}



/**
 * 初始化搜索
 */
function initSearch() {
  const searchToggle = document.getElementById("searchToggle")
  const searchContainer = document.getElementById("searchContainer")
  const closeSearch = document.getElementById("closeSearch")
  const searchForm = document.getElementById("searchForm")
  const searchInput = document.getElementById("searchInput")

  // 监听搜索按钮点击
  searchToggle?.addEventListener("click", () => {
    document.body.classList.add("search-open")    
    searchToggle.style.display = "none"
    searchContainer.style.display = "block"
    searchInput?.focus()
  })

  // 监听关闭搜索按钮点击
  closeSearch?.addEventListener("click", () => {
    document.body.classList.remove("search-open")
    searchToggle.style.display = "block"
    searchContainer.style.display = "none"
  })

  // 监听搜索表单提交
  searchForm?.addEventListener("submit", (e) => {
    e.preventDefault()
    const query = searchInput.value.trim()
    if (query) {
      window.location.href = `search.html?q=${encodeURIComponent(query)}`
    }
  })
}

/**
 * 初始化源切换下拉菜单
 */
function initSourceDropdown() {
  const sourceButton = document.getElementById("sourceButton")
  const sourceDropdown = document.getElementById("sourceDropdown")
  const sourceList = document.getElementById("sourceList")
  const addSourceBtn = document.getElementById("addSourceBtn")
  const addSourceModal = document.getElementById("addSourceModal")
  const closeAddSourceModal = document.getElementById("closeAddSourceModal")
  const cancelAddSource = document.getElementById("cancelAddSource")
  const saveSourceBtn = document.getElementById("saveSourceBtn")

  if (!sourceButton || !sourceDropdown || !sourceList) return

  // 渲染源列表
  renderSourceList()

  // 监听源切换按钮鼠标悬停
  sourceButton.addEventListener("mouseenter", () => {
    sourceDropdown.classList.add("open")
  })

  // 监听源下拉菜单鼠标悬停
  sourceDropdown.addEventListener("mouseenter", () => {
    sourceDropdown.classList.add("open")
  })

  // 监听源切换按钮和下拉菜单鼠标离开
  sourceButton.addEventListener("mouseleave", () => {
    setTimeout(() => {
      if (!sourceDropdown.matches(":hover")) {
        sourceDropdown.classList.remove("open")
      }
    }, 100)
  })

  sourceDropdown.addEventListener("mouseleave", () => {
    sourceDropdown.classList.remove("open")
  })

  // 监听添加源按钮点击
  addSourceBtn?.addEventListener("click", () => {
    sourceDropdown.classList.remove("open")
    resetAddSourceForm()
    addSourceModal.classList.add("open")
  })

  // 监听关闭添加源对话框按钮点击
  closeAddSourceModal?.addEventListener("click", () => {
    addSourceModal.classList.remove("open")
  })

  // 监听取消添加源按钮点击
  cancelAddSource?.addEventListener("click", () => {
    addSourceModal.classList.remove("open")
  })

  // 监听保存源按钮点击
  saveSourceBtn?.addEventListener("click", () => {
    const sourceName = document.getElementById("sourceName").value.trim()
    const sourceApi = document.getElementById("sourceApi").value.trim()
    const sourceProxy = document.getElementById("sourceProxy").value.trim()
    const sourceType = document.getElementById("sourceType").value

    if (!sourceName  || !sourceApi) {
      alert("请填写完整信息")
      return
    }

    const sourceId = `source_${Date.now()}`
    const newSource = {
      id: sourceId,
      name: sourceName,
      api: sourceApi,
      proxy: sourceProxy || "",
      type: sourceType,
    }

    window.AppConfig.addSource(newSource)
    window.AppConfig.setActiveSource(sourceId)

    addSourceModal.classList.remove("open")
    updateSidebarBadges()
    renderSourceList()

    // 显示成功提示
    showToast("添加源成功")

    // 刷新页面以应用新源
    setTimeout(() => {
      window.location.reload()
    }, 1000)
  })

  /**
   * 渲染源列表
   */
  function renderSourceList() {
    if (!sourceList) return

    const config = window.AppConfig.getConfig()
    const sources = config.sources
    const activeSourceId = config.activeSourceId

    sourceList.innerHTML = ""

    if (sources.length === 0) {
      sourceList.innerHTML = `
        <div class="source-dropdown-empty">
          <i class="ri-database-2-line"></i>
          <p>暂无媒体源</p>
        </div>
      `
      return
    }

    // 更新当前源名称
    const activeSource = sources.find((s) => s.id === activeSourceId)
    if (activeSource && sourceButton) {
      sourceButton.innerHTML = `
        <i class="ri-database-2-line"></i>
        <span>${activeSource.name}</span>
        <i class="ri-arrow-down-s-line"></i>
      `
    }

    sources.forEach((source) => {
      const isActive = source.id === activeSourceId
      const sourceItem = document.createElement("div")
      sourceItem.className = `source-dropdown-item ${isActive ? "active" : ""}`
      sourceItem.innerHTML = `
        <div class="source-dropdown-item-name">
          <span>${source.name}</span>
          ${isActive ? '<span class="source-dropdown-badge">当前</span>' : ""}
        </div>
      `

      if (!isActive) {
        sourceItem.addEventListener("click", (e) => {
          if (!e.target.closest(".source-dropdown-edit") && !e.target.closest(".source-dropdown-delete")) {
            window.AppConfig.setActiveSource(source.id)
            sourceDropdown.classList.remove("open")
            updateSidebarBadges()
            showToast("已切换媒体源")
            getCategory()
            // 刷新页面以应用新源
            setTimeout(() => {
              window.location.reload()
            }, 1000)
          }
        })
      }

      sourceList.appendChild(sourceItem)
    })

    // 添加编辑按钮事件
    document.querySelectorAll(".source-dropdown-edit").forEach((btn) => {
      btn.addEventListener("click", (e) => {
        e.stopPropagation()
        const sourceId = btn.dataset.id
        const source = config.sources.find((s) => s.id === sourceId)
        if (source) {
          document.getElementById("sourceName").value = source.name
          document.getElementById("sourceApi").value = source.api
          document.getElementById("sourceProxy").value = source.proxy || ""
          document.getElementById("sourceType").value = source.type

          // 修改保存按钮行为
          saveSourceBtn.onclick = () => {
            const updatedSource = {
              id: sourceId,
              name: document.getElementById("sourceName").value.trim(),
              api: document.getElementById("sourceApi").value.trim(),
              proxy: document.getElementById("sourceProxy").value.trim(),
              type: document.getElementById("sourceType").value,
            }

            if (!updatedSource.name || !updatedSource.url || !updatedSource.api) {
              alert("请填写完整信息")
              return
            }

            window.AppConfig.updateSource(sourceId, updatedSource)
            addSourceModal.classList.remove("open")
            sourceDropdown.classList.remove("open")
            updateSidebarBadges()
            renderSourceList()

            // 显示成功提示
            showToast("更新源成功")

            // 如果是当前源，刷新页面
            if (sourceId === config.activeSourceId) {
              setTimeout(() => {
                window.location.reload()
              }, 1000)
            }
          }

          sourceDropdown.classList.remove("open")
          addSourceModal.classList.add("open")
        }
      })
    })

    // 添加删除按钮事件
    document.querySelectorAll(".source-dropdown-delete").forEach((btn) => {
      btn.addEventListener("click", (e) => {
        e.stopPropagation()
        const sourceId = btn.dataset.id
        if (confirm("确定要删除这个媒体源吗？")) {
          window.AppConfig.deleteSource(sourceId)
          renderSourceList()
          updateSidebarBadges()
          sourceDropdown.classList.remove("open")

          // 如果删除的是当前源，刷新页面
          if (sourceId === config.activeSourceId) {
            setTimeout(() => {
              window.location.reload()
            }, 1000)
          }
        }
      })
    })

    // 添加"添加源"按钮
    const addButton = document.createElement("div")
    addButton.className = "source-dropdown-add"
    addButton.innerHTML = `
      <i class="ri-add-line"></i>
      <span>添加媒体源</span>
    `
    addButton.addEventListener("click", () => {
      sourceDropdown.classList.remove("open")
      resetAddSourceForm()
      addSourceModal.classList.add("open")
    })
    sourceList.appendChild(addButton)
    
  }

  /**
   * 重置添加源表单
   */
  function resetAddSourceForm() {
    document.getElementById("sourceName").value = ""
    document.getElementById("sourceApi").value = ""
    document.getElementById("sourceProxy").value = ""
    document.getElementById("sourceType").value = "movie"

    // 重置保存按钮行为
    saveSourceBtn.onclick = () => {
      const sourceName = document.getElementById("sourceName").value.trim()
      const sourceApi = document.getElementById("sourceApi").value.trim()
      const sourceProxy = document.getElementById("sourceProxy").value.trim()
      const sourceType = document.getElementById("sourceType").value

      if (!sourceName || !sourceApi) {
        alert("请填写完整信息")
        return
      }

      const sourceId = `source_${Date.now()}`
      const newSource = {
        id: sourceId,
        name: sourceName,
        api: sourceApi,
        proxy: sourceProxy || "",
        type: sourceType,
      }

      window.AppConfig.addSource(newSource)
      window.AppConfig.setActiveSource(sourceId)

      addSourceModal.classList.remove("open")
      updateSidebarBadges()
      renderSourceList()

      // 显示成功提示
      showToast("添加源成功")

      // 刷新页面以应用新源
      setTimeout(() => {
        window.location.reload()
      }, 1000)
    }
  }
}

/**
 * 初始化主题切换对话框
 */
function initThemeModal() {
  const themeModal = document.getElementById("themeModal")
  const closeThemeModal = document.getElementById("closeThemeModal")
  const themeOptions = document.querySelectorAll(".theme-option")

  // 监听关闭按钮点击
  closeThemeModal?.addEventListener("click", () => {
    themeModal.classList.remove("open")
  })

  // 监听主题选项点击
  themeOptions.forEach((option) => {
    option.addEventListener("click", () => {
      const theme = option.dataset.theme

      // 更新主题
      document.body.className = `theme-${theme}`
      window.AppConfig.updateNestedConfig("ui.theme", theme)

      // 更新主题切换按钮图标
      const themeToggleBtn = document.getElementById("themeToggle")
      if (themeToggleBtn) {
        themeToggleBtn.innerHTML = theme === "dark" ? '<i class="ri-sun-line"></i>' : '<i class="ri-moon-line"></i>'
      }

      // 关闭对话框
      themeModal.classList.remove("open")

      // 显示成功提示
      showToast("主题已更新")
    })
  })
}

/**
 * 初始化下拉菜单
 */
function initDropdowns() {
  const dropdowns = document.querySelectorAll(".dropdown")

  dropdowns.forEach((dropdown) => {
    const toggle = dropdown.querySelector(".dropdown-toggle")

    toggle?.addEventListener("click", (e) => {
      e.stopPropagation()

      // 关闭其他下拉菜单
      dropdowns.forEach((d) => {
        if (d !== dropdown) {
          d.classList.remove("open")
        }
      })

      // 切换当前下拉菜单
      dropdown.classList.toggle("open")
    })
  })

  // 点击页面其他地方关闭下拉菜单
  document.addEventListener("click", () => {
    dropdowns.forEach((dropdown) => {
      dropdown.classList.remove("open")
    })
  })
}

/**
 * 初始化设置按钮
 */
function initSettingsButton() {
  const settingsButton = document.getElementById("settingsButton")

  if (settingsButton) {
    settingsButton.addEventListener("click", () => {
      window.location.href = "settings.html"
    })
  }
}

/**
 * 初始化媒体卡片交互
 */
function initMediaCardInteractions() {
  // 创建媒体卡片时添加交互元素
  document.addEventListener("mediaCardCreated", (e) => {
    const card = e.detail
    if (!card) return

    addMediaCardControls(card)
  })

  // 为现有的媒体卡片添加交互元素
  document.querySelectorAll(".media-card").forEach((card) => {
    addMediaCardControls(card)
  })

  // 初始化媒体操作菜单
  initMediaActionMenu()
}

/**
 * 为媒体卡片添加控件
 * @param {HTMLElement} card 媒体卡片元素
 */
function addMediaCardControls(card) {
  // 获取媒体ID
  const mediaId = card.dataset.id || "0"
  const mediaTitle = card.dataset.title || "未知标题"

  // 创建控件容器
  const controlsContainer = document.createElement("div")
  controlsContainer.className = "media-controls"

  // 添加播放按钮
  const playButton = document.createElement("button")
  playButton.className = "play-button"
  playButton.innerHTML = '<i class="ri-play-fill"></i>'
  playButton.addEventListener("click", (e) => {
    e.preventDefault()
    e.stopPropagation()
    window.location.href = `detail.html?id=${mediaId}`
  })

  // 添加操作按钮容器
  const actionsContainer = document.createElement("div")
  actionsContainer.className = "media-actions"

  // 添加标记按钮
  const markButton = document.createElement("button")
  markButton.className = "action-button"
  markButton.innerHTML = '<i class="ri-check-line"></i>'
  markButton.title = "标记为已看"
  markButton.addEventListener("click", (e) => {
    e.preventDefault()
    e.stopPropagation()
    toggleWatched(mediaId, markButton)
  })

  // 添加收藏按钮
  const favoriteButton = document.createElement("button")
  favoriteButton.className = "action-button"
  favoriteButton.innerHTML = '<i class="ri-heart-line"></i>'
  favoriteButton.title = "添加到收藏"
  favoriteButton.addEventListener("click", (e) => {
    e.preventDefault()
    e.stopPropagation()
    toggleFavorite(mediaId, favoriteButton)
  })

  // 添加菜单按钮
  const menuButton = document.createElement("button")
  menuButton.className = "action-button"
  menuButton.innerHTML = '<i class="ri-more-2-fill"></i>'
  menuButton.title = "更多操作"
  menuButton.addEventListener("click", (e) => {
    e.preventDefault()
    e.stopPropagation()
    showMediaActionMenu(e, mediaId, mediaTitle)
  })

  // 组装控件
  actionsContainer.appendChild(markButton)
  actionsContainer.appendChild(favoriteButton)
  actionsContainer.appendChild(menuButton)

  controlsContainer.appendChild(playButton)
  controlsContainer.appendChild(actionsContainer)

  // 添加到卡片
  card.appendChild(controlsContainer)

  // 更新按钮状态
  updateButtonStates(mediaId, markButton, favoriteButton)
}

/**
 * 切换已看状态
 * @param {string} mediaId 媒体ID
 * @param {HTMLElement} button 按钮元素
 */
function toggleWatched(mediaId, button) {
  // 获取已看列表
  let watched = localStorage.getItem("mediaWatched")
  watched = watched ? JSON.parse(watched) : []

  // 检查是否已标记
  const isWatched = watched.includes(mediaId)

  if (isWatched) {
    // 移除标记
    watched = watched.filter((id) => id !== mediaId)
    button.classList.remove("active")
    showToast("已移除标记")
  } else {
    // 添加标记
    watched.push(mediaId)
    button.classList.add("active")
    showToast("已标记为已看")
  }

  // 保存到本地存储
  localStorage.setItem("mediaWatched", JSON.stringify(watched))
}

/**
 * 切换收藏状态
 * @param {string} mediaId 媒体ID
 * @param {HTMLElement} button 按钮元素
 */
function toggleFavorite(mediaId, button) {
  // 检查是否已收藏
  const isFavorited = window.API.isFavorite(mediaId)

  if (isFavorited) {
    // 移除收藏
    const success = window.API.removeFavorite(mediaId)
    if (success) {
      button.classList.remove("active")
      button.innerHTML = '<i class="ri-heart-line"></i>'
      showToast("已移除收藏")
    }
  } else {
    // 获取媒体详情并添加收藏
    const activeSource = window.AppConfig.getActiveSource()
    if (activeSource) {
      window.API.getMediaDetail(activeSource, mediaId).then((media) => {
        if (media) {
          const success = window.API.addFavorite(media)
          if (success) {
            button.classList.add("active")
            button.innerHTML = '<i class="ri-heart-fill"></i>'
            showToast("已添加到收藏")
          }
        }
      })
    }
  }
}

/**
 * 显示媒体操作菜单
 * @param {Event} event 事件对象
 * @param {string} mediaId 媒体ID
 * @param {string} mediaTitle 媒体标题
 */
function showMediaActionMenu(event, mediaId, mediaTitle) {
  // 检查菜单是否存在，如果不存在则创建
  let menu = document.getElementById("mediaActionMenu")
  if (!menu) {
    menu = document.createElement("div")
    menu.id = "mediaActionMenu"
    menu.className = "media-action-menu"
    menu.innerHTML = `
      <div class="action-menu-item" data-action="match">
        <i class="ri-edit-line"></i>
        <span>手动匹配影片</span>
      </div>
      <div class="action-menu-item" data-action="unmatch">
        <i class="ri-link-unlink"></i>
        <span>解除匹配影片</span>
      </div>
      <div class="action-menu-item" data-action="delete">
        <i class="ri-delete-bin-line"></i>
        <span>删除</span>
      </div>
    `
    document.body.appendChild(menu)

    // 初始化菜单项点击事件
    menu.querySelectorAll(".action-menu-item").forEach((item) => {
      item.addEventListener("click", () => {
        const action = item.dataset.action
        const mediaId = menu.dataset.mediaId
        const mediaTitle = menu.dataset.mediaTitle

        // 执行相应操作
        switch (action) {
          case "match":
            showToast(`手动匹配影片: ${mediaTitle}`)
            break
          case "unmatch":
            showToast(`解除匹配影片: ${mediaTitle}`)
            break
          case "delete":
            if (confirm(`确定要删除 ${mediaTitle} 吗？`)) {
              showToast(`已删除: ${mediaTitle}`)
            }
            break
        }

        // 隐藏菜单
        menu.style.display = "none"
      })
    })
  }

  // 设置菜单位置
  const rect = event.target.getBoundingClientRect()
  menu.style.top = `${rect.bottom + window.scrollY + 5}px`
  menu.style.left = `${rect.left + window.scrollX - 150}px` // 向左偏移以对齐

  // 设置菜单数据
  menu.dataset.mediaId = mediaId
  menu.dataset.mediaTitle = mediaTitle

  // 显示菜单
  menu.style.display = "block"

  // 点击其他地方关闭菜单
  const closeMenu = (e) => {
    if (!menu.contains(e.target) && e.target !== event.target) {
      menu.style.display = "none"
      document.removeEventListener("click", closeMenu)
    }
  }

  // 延迟添加事件监听，避免立即触发
  setTimeout(() => {
    document.addEventListener("click", closeMenu)
  }, 0)
}

/**
 * 初始化媒体操作菜单
 */
function initMediaActionMenu() {
  const menu = document.getElementById("mediaActionMenu")
  if (!menu) return

  // 监听菜单项点击
  menu.querySelectorAll(".action-menu-item").forEach((item) => {
    item.addEventListener("click", () => {
      const action = item.dataset.action
      const mediaId = menu.dataset.mediaId
      const mediaTitle = menu.dataset.mediaTitle

      // 执行相应操作
      switch (action) {
        case "match":
          showToast(`手动匹配影片: ${mediaTitle}`)
          break
        case "unmatch":
          showToast(`解除匹配影片: ${mediaTitle}`)
          break
        case "delete":
          if (confirm(`确定要删除 ${mediaTitle} 吗？`)) {
            showToast(`已删除: ${mediaTitle}`)
          }
          break
      }

      // 隐藏菜单
      menu.style.display = "none"
    })
  })
}

/**
 * 更新按钮状态
 * @param {string} mediaId 媒体ID
 * @param {HTMLElement} markButton 标记按钮
 * @param {HTMLElement} favoriteButton 收藏按钮
 */
function updateButtonStates(mediaId, markButton, favoriteButton) {
  // 更新标记按钮状态
  let watched = localStorage.getItem("mediaWatched")
  watched = watched ? JSON.parse(watched) : []

  if (watched.includes(mediaId)) {
    markButton.classList.add("active")
  }

  // 更新收藏按钮状态
  const isFavorited = window.API.isFavorite(mediaId)
  if (isFavorited) {
    favoriteButton.classList.add("active")
    favoriteButton.innerHTML = '<i class="ri-heart-fill"></i>'
  }
}

/**
 * 创建媒体卡片
 * @param {Object} item 媒体项
 * @returns {HTMLElement} 媒体卡片元素
 */
function createMediaCard(item) {
  const card = document.createElement("a")
  card.href = `detail.html?id=${item.vod_id}`
  card.className = "media-card"
  card.dataset.id = item.vod_id
  card.dataset.title = item.vod_name
  //console.log(item)
  const posterUrl = item.vod_pic || `images/placeholder.jpg`

  card.innerHTML = `
    <div class="media-poster">
      <img src="${posterUrl}" alt="${item.vod_name}" loading="lazy">
      ${item.vod_remarks ? `<div class="media-badge">${item.vod_remarks}</div>` : ""}
    </div>
    <div class="media-overlay">
      <div class="media-title">${item.vod_name}</div>
    </div>
  `

  // 触发媒体卡片创建事件
  document.dispatchEvent(new CustomEvent("mediaCardCreated", { detail: card }))

  return card
}

/**
 * 显示提示消息
 * @param {string} message 消息内容
 * @param {string} type 消息类型 (success, error, info)
 * @param {number} duration 显示时长 (毫秒)
 */
function showToast(message, type = "success", duration = 3000) {
  // 检查是否已存在 toast 容器
  let toastContainer = document.querySelector(".toast-container")

  if (!toastContainer) {
    toastContainer = document.createElement("div")
    toastContainer.className = "toast-container"
    document.body.appendChild(toastContainer)
  }

  // 创建 toast 元素
  const toast = document.createElement("div")
  toast.className = `toast toast-${type}`

  // 设置图标
  let icon = "ri-check-line"
  if (type === "error") icon = "ri-error-warning-line"
  if (type === "info") icon = "ri-information-line"

  toast.innerHTML = `
    <i class="${icon}"></i>
    <span>${message}</span>
  `

  // 添加到容器
  toastContainer.appendChild(toast)

  // 添加显示类
  setTimeout(() => {
    toast.classList.add("show")
  }, 10)

  // 设置自动消失
  setTimeout(() => {
    toast.classList.remove("show")

    // 移除元素
    setTimeout(() => {
      toast.remove()
    }, 300)
  }, duration)
}

function creatListLoading(element,num) {
  for (let i = 0; i < num; i++) {
    const loadingItem = document.createElement("div");
    loadingItem.className = "media-skeleton";
    element.appendChild(loadingItem);
  }
}
function removeListLoading(callback=()=>{}){
  callback()
  const mediaSkeletons = document.querySelectorAll(".media-skeleton");
  mediaSkeletons.forEach((skeleton) => {
    skeleton.remove();
  });
}


// 导出函数
window.UI = {
  createMediaCard,
  showToast,
  updateSidebarBadges,
}
